# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
  
  PERSON_DOES_NOT_EXIST = "您想找的人不存在"
  
  def check_authentication
    unless session[:user]
      session[:intended_controller] = controller_name
      session[:intended_action] = action_name
      ask_for_sign_in
    else
      begin 
        @user = User.find(session[:user])
      rescue
        ask_for_sign_in
      end
    end
  end
  
  def admin_authentication
    check_authentication
    unless User.is_admin(session[:user])
      ask_for_sign_in "您的权限不够，如果您是管理员，请重新登录."
    end
  end
  
  private
  def render_error_page(message)
    flash[:error] = message
    render :template => 'error_page.rhtml'
  end
  
  def ask_for_sign_in(message = "请用您的用户名登录")
    flash[:notice] = message
    redirect_to(:controller => "users", :action => "signin") 
  end
  
  def find_user_and_render_public_page
    @person = User.find_by_username(params[:username])
    if @person.nil?
      render_error_page PERSON_DOES_NOT_EXIST
    else
      render :layout => 'public_page'
    end
  end
end

class IllegalParameterException < StandardError ;end
